package com.wbs.shop.nuby.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.wbs.shop.nuby.App;
import com.wbs.shop.nuby.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;

/**
 * Created by Administrator on 2017/3/21 0021.
 */

public class Utils {
    public static Context context;

    public static void init(Context context) {
        Utils.context = context;
    }

    public static boolean isTextViewValueEmpty(View textView) {
        return StringUtils.isEmpty(getTextViewValue(textView));
    }

    public static String getTextViewValue(View textView) {
        return getTextViewValue((TextView) textView);
    }

    public static String getTextViewValue(TextView textView) {
        return textView.getText().toString().trim();
    }

    public static void toastMessageShort(String text) {
        toastMessageShort(context, text);
    }

    public static void toastMessageLong(String text) {
        toastMessageLong(context, text);
    }

    private static void toastMessageShort(Context context, String text) {
        toastMessage(context, text, Toast.LENGTH_SHORT);
    }

    private static void toastMessageLong(Context context, String text) {
        toastMessage(context, text, Toast.LENGTH_LONG);
    }

    // Toast对象
    private static Toast toast = null;

    private static void toastMessage(Context context, String text, int duration) {
        if (toast == null) {
            toast = Toast.makeText(context, text, duration);
        }
        toast.setText(text);
        toast.show();
    }

    public static void callPhone(Context context, String phone) {
        Uri uri;
        if ("tel:".startsWith(phone)) {
            uri = Uri.parse(phone);
        } else {
            uri = Uri.parse("tel:" + phone);
        }
        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void setTextNotEmpty(TextView view, Object value, String def) {
        view.setText(value == null ? def : value + "");
    }

    public static void setTextNotEmpty(TextView view, Object value) {
        setTextNotEmpty(view, value, "");
    }

    public static File getAppRootPath(Context context) {
        if (sdCardIsAvailable()) {
            return Environment.getExternalStorageDirectory();
        } else {
            return context.getFilesDir();
        }
    }

    public static boolean sdCardIsAvailable() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().canWrite();
        } else
            return false;
    }

    /**
     * 判断是否为平板
     *
     * @return
     */
    public static boolean isPad() {
        WindowManager wm = (WindowManager) App.getApp().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        float screenWidth = display.getWidth();
        // 屏幕高度
        float screenHeight = display.getHeight();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
        double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
        // 屏幕尺寸
        double screenInches = Math.sqrt(x + y);
        // 大于6尺寸则为Pad
        if (screenInches >= 7.0) {
            return true;
        }
        return false;
        // Verifies if the Generalized Size of the device is XLARGE to be
        // considered a Tablet
//        boolean xlarge = ((App.getApp().getResources().getConfiguration().screenLayout &
//                Configuration.SCREENLAYOUT_SIZE_MASK) ==
//                Configuration.SCREENLAYOUT_SIZE_XLARGE);
//
//        // If XLarge, checks if the Generalized Density is at least MDPI
//        // (160dpi)
//        if (xlarge) {
//            DisplayMetrics metrics = new DisplayMetrics();
//            WindowManager wm = (WindowManager) App.getApp().getSystemService(Context.WINDOW_SERVICE);
//            wm.getDefaultDisplay().getMetrics(metrics);
//
//            // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
//            // DENSITY_TV=213, DENSITY_XHIGH=320
//            if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
//                    || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
//                    || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
//                    || metrics.densityDpi == DisplayMetrics.DENSITY_TV
//                    || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
//
//                // Yes, this is a tablet!
//                return true;
//            }
//        }
//
//        // No, this is not a tablet!
//        return false;
    }

    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        try {
            // 首先保存图片
            String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "salon_m";
            File appDir = new File(storePath);
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".jpg";
            File file = new File(appDir, fileName);
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            //把文件插入到系统图库
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            return isSuccess;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static BitmapFactory.Options getBitmapOptions(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        return options;
    }

    public static String getProjectNo(String prefix) {
        StringBuilder projectNo = new StringBuilder(prefix);
        Random random = new Random();
        Calendar calendar = Calendar.getInstance();
        projectNo.append(calendar.get(Calendar.YEAR));
        projectNo.append(calendar.get(Calendar.MONTH));
        projectNo.append(calendar.get(Calendar.DAY_OF_MONTH));
        projectNo.append(random.nextInt(9));
        projectNo.append(random.nextInt(9));
        return projectNo.toString();
    }

    private static SimpleDateFormat sdf = null;

    public synchronized static String formatUTC(long l, String strPattern) {
        if (TextUtils.isEmpty(strPattern)) {
            strPattern = "yyyy-MM-dd HH:mm:ss";
        }
        if (sdf == null) {
            try {
                sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
            } catch (Throwable e) {
            }
        } else {
            sdf.applyPattern(strPattern);
        }
        return sdf == null ? "NULL" : sdf.format(l);
    }

    /**
     * 滤镜定义
     */
    public static final int FILTERTYPE_NONE = 0;    //无特效滤镜
    public static final int FILTERTYPE_langman = 1;    //浪漫滤镜
    public static final int FILTERTYPE_qingxin = 2;    //清新滤镜
    public static final int FILTERTYPE_weimei = 3;    //唯美滤镜
    public static final int FILTERTYPE_fennen = 4;    //粉嫩滤镜
    public static final int FILTERTYPE_huaijiu = 5;    //怀旧滤镜
    public static final int FILTERTYPE_landiao = 6;    //蓝调滤镜
    public static final int FILTERTYPE_qingliang = 7;    //清凉滤镜
    public static final int FILTERTYPE_rixi = 8;    //日系滤镜

    private static Bitmap decodeResource(Resources resources, int id) {
        TypedValue value = new TypedValue();
        resources.openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(resources, id, opts);
    }


    /**
     * 根据比例转化实际数值为相对值
     *
     * @param gear 档位
     * @param max  最大值
     * @param curr 当前值
     * @return 相对值
     */
    public static int filtNumber(int gear, int max, int curr) {
        return curr / (max / gear);
    }

    public static int getMeatIcon(Context context, Class<?> clz, String key) {
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            String welcomePath = info.metaData.getString(key);
            Field[] fields = clz.getFields();
            for (Field field : fields) {
                String substring = welcomePath.substring(welcomePath.lastIndexOf("/") + 1, welcomePath.lastIndexOf("."));
                if (field.getName().equals(substring)) {
                    return (int) field.get(null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getMeatDataString(Context context, String key) {
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 将Bitmap转换成InputStream(压缩率quality、100表示不压缩、10表示压缩90%)
    public static InputStream Bitmap2InputStream(Bitmap bm, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
        return new ByteArrayInputStream(baos.toByteArray());
    }

    // 将Bitmap转换成InputStream
    public static InputStream Bitmap2InputStream(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return new ByteArrayInputStream(baos.toByteArray());
    }

    public static void showView(View... view) {
        if (view != null && view.length > 0) {
            for (View viewItem : view) {
                showView(viewItem);
            }
        }
    }

    public static void showView(View view) {
        if (view != null && view.getVisibility() == View.GONE) {
            view.setVisibility(View.VISIBLE);
        }
    }

    public static void hideView(View... view) {
        if (view != null && view.length > 0) {
            for (View viewItem : view) {
                hideView(viewItem);
            }
        }
    }

    public static void hideSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    public static void hideView(View view) {
        if (view != null && view.getVisibility() == View.VISIBLE) {
            view.setVisibility(View.GONE);
        }
    }

    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    public static int random8() {
        StringBuilder random = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            random.append(String.valueOf((int) (Math.random() * 10)));
        }
        return Integer.parseInt(random.toString());
    }

    public static String getDouble(String d) {
        if (d == null || d.length() == 0)
            return "0";
        d = d.replaceAll("0+?$", "");//去掉后面无用的零
        d = d.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
        return d;
    }

    public static boolean isUpdate(Context context, String serviceVersion) {
        boolean isUpdate = false;
        try {
            String versionName = context.getString(R.string.version_name);
            String[] versionNameArr = versionName.split("\\.");
            String[] serviceVersionArr = serviceVersion.split("\\.");
            // 本地小于服务器更新1.0  1.1
            for (int i = 0; i < Math.min(versionNameArr.length, serviceVersionArr.length); i++) {
                int local = Integer.parseInt(versionNameArr[i]);
                int service = Integer.parseInt(serviceVersionArr[i]);
                if (local < service) {
                    isUpdate = true;
                    break;
                } else if (local == service) {// 跳过

                } else {// 本地大于远端，不更新
                    break;
                }
            }
            if (!isUpdate && versionNameArr.length < serviceVersionArr.length) {
                isUpdate = true;
            }
        } catch (Exception e) {
            Logger.e(e);
        }
        return isUpdate;
    }
}
